from watchdog.observers import Observer
from watchdog.events import *
from config import watch_files,to_mails,watch_file_interval
import yagmail
import time


def read_warning(filepath):
    error_result = []
    try :
        with open(filepath) as file :
            for line in file:
                if "error" in line:

                    error_result.append(line)
    except Exception as e:
        print(e)
    finally:
        pass
    # with open(filepath,'rb') as file:
    #     for i in file:
    #         if i:
    #             error_result.append(i)
    # if len(error_result) == 0 :
    #     return []
    return error_result


def send_mail(context):
    yag = yagmail.SMTP(user='test@huodao.hk', password='Zhaoliangji2017', smtp_starttls=True, host='smtp.exmail.qq.com',
                       port=587)
    yag.send(to=to_mails, subject='爬虫报告',contents=['爬虫出错了，错误日志是：' + context])
    print("mail has been sent")


class Myhandler(FileSystemEventHandler):
    def on_any_event(self, event):

        filepath = event.src_path
        if filepath[-3:] == "log":
            errors = read_warning(filepath)
            print(errors)
            if len(errors) == 0:
                pass
            else:
                send_mail('\n'.join(errors))

if __name__ == "__main__":
    hander = Myhandler()
    watchdogs = []
    for i in watch_files:
        obsert = Observer()
        obsert.schedule(hander,i,True)
        obsert.start()
        watchdogs.append(obsert)
    try :
        while True:
            time.sleep(watch_file_interval)
    except KeyboardInterrupt:
        for i in watchdogs:
            i.stop()
    for i in watchdogs:
        i.join()






